package ImplementChat;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/*服务器：
1.建立服务的端口 ServerSocket
2.等待用户的链接 accept
3.接受用户的消息*/
public class TcpServer {


    public static void main(String[] args) {
        //提升作用域
        ServerSocket serverSocket = null;
        Socket accept = null;
        InputStream inputStream = null;
        ByteArrayOutputStream baos = null;
        try {
            //设置了一个地址，端口号为9999
             serverSocket = new ServerSocket(9999);
            //等待客户端连接过来
            accept = serverSocket.accept();
            //读取客户端消息
            inputStream = accept.getInputStream();
            
            //管道流
            baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while((len = inputStream.read(buffer))!=-1){
                baos.write(buffer,0,len);
            }
            System.out.println(baos.toString());



        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            //关闭资源
            if(baos!=null){
                try {
                    baos.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if(baos!=null){
                try {
                    baos.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }            if(baos!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }            if(baos!=null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }




        }
    }
}
